package com.arron.algorithm;

/**
 * @Classname ReverseList
 * @Date 2020/9/11 14:49
 * @Created by 刘
 *
 * 链表反转
 *
 */


public class ReverseList {

    public static void main(String[] args) {

        ListNode listNode = buildListNodes();
        System.out.println("==========反转之前的链表==================");
        printListNode(listNode);

        //反转链表
        ListNode reverse = reverse(listNode);
        System.out.println("==========反转之后的链表==================");
        printListNode(reverse);

    }

    private static ListNode buildListNodes() {
        ListNode listNode = new ListNode(0);
        ListNode temp = listNode;
        ListNode cur = null;
        for (int i = 1; i <= 3; i++) {
            cur = temp;
            cur.next = new ListNode(i);
            temp = cur.next;
        }
        return listNode;
    }

    /**
     * 链表的反转
     * @param headNode
     */
    public static ListNode reverse(ListNode headNode){

        //1.判断链表是否为null
        if (headNode == null){
            return null;
        }
        ListNode temp = null;
        ListNode pre = null;
        ListNode cur = headNode;
        //循环反转链表
        while (cur!=null){
            //指向cur的下一个节点
            temp = cur.next;
            //让当前的节点的指向前面一个节点
            cur.next = pre;
            //将前一个节点移动到下一个节点
            pre = cur;
            //移动当前节点
            cur = temp;
        }
        //循环结束，反转链表结束
        return pre;
    }

    /**
     * 打印链表
     * @param head
     */
    public static void printListNode(ListNode head){

        if (head == null){
            return;
        }

        ListNode cur = head;

        while (cur !=null ){
            System.out.println(cur.val);
            cur = cur.next;
        }

    }
}
